import React, { useEffect, useRef, useState } from 'react'
import { connect } from 'react-redux'
import { Button, Input } from 'antd'
import useCaptcha, { ISMCaptchaInstance } from '../../hooks/useCaptcha'
import { useHistory } from 'react-router-dom'
import { isEmpty } from 'lodash'
import { isValidMobile } from '../../utils/validation'
import { ISendMobileVerifyCodeParam } from '../../service/typing/service/IClientService'
import { serviceContext } from '../../service/context'
import { E_ERROR_CODE } from '../../service/typing/enum/error-code'
import { IAuthAction, setIsLoggedIn, setToken, setUserId } from '../../store/modules/auth'
import './Login.less'
import MobileInput from '../../components/mobile-input/MobileInput'
import { ILoginParam } from '../../service/typing/service/IAuthService'
import { E_ROUTE_PATH } from '../../router/route-path'
import CountryCodeSelect from '../../components/country-code-select/CountryCodeSelect'
import { localStorageUtil } from '../../utils/storage'
import { E_UI_STORAGE_KEY } from '../../constant/ui-constant'

export interface ILoginProps {}
type IActionProps = Partial<IAuthAction>

type ILoginAllProps = ILoginProps & IActionProps

function Login(props: ILoginAllProps) {
  const captchaInstance = useRef<ISMCaptchaInstance>()
  let captcha: string = ''
  const mobileRef = useRef('')
  const history = useHistory()

  const [countryCode, setCountryCode] = useState('86')
  const [errorMsg, setErrorMsg] = useState('')
  const [mobile, setMobile] = useState('')
  const [verifyCode, setVerifyCode] = useState('')

  function verifyTextCode() {
    captchaInstance.current?.reset()
    captchaInstance.current?.verify()
  }

  function checkInput() {
    if (isEmpty(mobile)) {
      setErrorMsg('请输入手机号码')
      return false
    }

    if (!isValidMobile(mobile)) {
      setErrorMsg('请输入正确的手机号码')
      return false
    }
    if (isEmpty(verifyCode)) {
      setErrorMsg('请输入短信验证码')
      return false
    }

    return true
  }

  async function sendVerifyCode() {
    const param: ISendMobileVerifyCodeParam = {
      countryCode: countryCode,
      mobile: mobileRef.current,
      captchaValidate: captcha
    }
    const result = await serviceContext.get().client.sendMobileVerifyCode(param)
    if (result.errorCode === E_ERROR_CODE.SUCCESS) {
      const data = result.data
      if (!isEmpty(data?.verifyCode)) {
        setVerifyCode(data!!.verifyCode)
      }
    }
  }

  useCaptcha({
    onReady: instance => {
      captchaInstance.current = instance
    },
    onSuccess: data => {
      if (data.pass) {
        captcha = data.rid

        sendVerifyCode()
      }
    },
    onError: () => {}
  })

  async function login() {
    const param: ILoginParam = {
      countryCode: countryCode,
      mobile: mobile,
      verifyCode,
      productId: 60000
    }

    const result = await serviceContext.get().auth.login(param)
    if (result.errorCode === E_ERROR_CODE.SUCCESS) {
      props.setIsLoggedIn && props.setIsLoggedIn(true)
      const token = result.data?.token || ''
      props.setToken && props.setToken(token)
      const userId = result.data?.umsUserId || 0
      props.setUserId && props.setUserId(userId)

      history.replace(E_ROUTE_PATH.COURSE_LIST)
    } else {
      setErrorMsg(result.errorMsg || '')
    }
  }

  function onLoginBtnClicked() {
    setErrorMsg('')
    const isPassed = checkInput()
    if (!isPassed) {
      return
    }
    login()
  }

  function onMobileChanged(value: string) {
    setMobile(value)
    mobileRef.current = value
  }

  useEffect(() => {
    const localMobile = localStorageUtil.getData(E_UI_STORAGE_KEY.KEY_MOBILE)
    if (localMobile) {
      setMobile(localMobile as string)
    }
  }, [])

  return (
    <div className="login">
      <div className="form-container">
        <div className="form">
          <div className="title">手机号登录</div>
          <div className={!!errorMsg ? 'error-msg msg-tips' : 'error-msg msg-tips hide'} title={errorMsg}>
            {errorMsg}
          </div>

          <div className="mobile-input-node">
            <CountryCodeSelect defaultValue={countryCode} bordered={false} className="country-code" onChange={value => setCountryCode(value)} />
            <div className="v-divider" />
            <MobileInput
              className="input-mobile input"
              placeholder="手机号"
              bordered={false}
              allowClear
              value={mobile}
              onValueChange={onMobileChanged}
            />
          </div>

          <div className="h-divider" />

          <div className="input-verify-code-node">
            <Input
              className="input-verify-code input"
              value={verifyCode}
              placeholder="短信验证码"
              bordered={false}
              allowClear
              onChange={e => setVerifyCode(e.target.value)}
            />
            <Button disabled={!isValidMobile(mobile)} className="btn-send-verify-code" type="link" onClick={() => verifyTextCode()}>
              获取验证码
            </Button>
          </div>
          <div className="h-divider" />

          <Button className="btn-login" type="primary" shape="round" onClick={onLoginBtnClicked}>
            快速登录
          </Button>
        </div>
      </div>
    </div>
  )
}

const mapAction = {
  setIsLoggedIn,
  setToken: setToken,
  setUserId: setUserId
}

export default connect(null, mapAction)(Login)
